<template>
  <!--页面搭建-cdfy2-->
  <div class="organization">
    <div class="organizationLeft">
        <keep-alive>
            <div class="companyTree">
                <div class="title">组织架构</div>
                <el-input class="search" v-model="filterText" :suffix-icon="Search" placeholder="搜索单位名称"/>
                <el-tree ref="treeRefs"
                         :data="treeData"
                         :props="defaultProps"
                         default-expand-all
                         :filter-node-method="filterNode"
                         node-key="id"
                         :expand-on-click-node="false"
                         @node-click="handleNodeClick"
                         highlight-current>
                </el-tree>
            </div>
        </keep-alive>
    </div>
    <div class="organizationRight">
      <layout-card
        v-model="retrievedForm"
        :filters="exampleOptions"
        headline="信息列表"
        headtitle="数据查询"
        :hasButton="true"
        @search-change="pageInfo"
        @search-reset="searchReset">
        <template #action>
          <el-button type="danger" plain :disabled="batchBtn" @click="review(1)">批量驳回</el-button>
            <el-popconfirm
                class="link-btn"
                title="是否批量通过?"
                confirmButtonText="确定"
                cancelButtonText="取消"
                @confirm="() => reviewanySub3()"
            >
                <template #reference>
                    <el-button type="primary" :disabled="batchBtn">批量通过</el-button>
                </template>
            </el-popconfirm>
          <el-button type="primary" @click="openTimeDialog">截止日期</el-button>
<!--          <el-button type="primary">发布</el-button>-->
          <el-popconfirm
              class="link-btn"
              title="是否批量发布?"
              confirmButtonText="确定"
              cancelButtonText="取消"
              @confirm="() => patchPublish2()"
          >
            <template #reference>
              <el-button type="primary" :disabled="patchBtn">批量发布</el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" :disabled="list.length === 0" :loading="exportLoading" @click="exportBtn">导出</el-button>
        </template>
        <table-common
          stripe="true"
          :columns="exampleColumns"
          :loading="loading"
          :pagination="pager"
          :table-data="list"
          size="small"
          @selection-change="handleSelectionChange"
          @current-change="changeCurrent"
          @size-change="changePageSize"
          @sort-change="sortChange">
          <template #operate="{ row }">
            <!-- 自定义操作栏示例  -->
              <el-button
                  class="link-btn"
                  link
                  type="primary"
                  v-if="row.status==1||row.status==0"
                  @click="openSubPage(row,1)"
              >新增奖惩记录
              </el-button>
            <el-popconfirm
                class="link-btn"
                title="是否发布?"
                confirmButtonText="确定"
                cancelButtonText="取消"
                @confirm="() => patchPublish(row)"
            >
                <template #reference>
                    <span>
                        <el-button
                            class="link-btn"
                            link
                            v-if="row.status == 0"
                            type="primary">发布
                    </el-button>
                    </span>
                </template>
            </el-popconfirm>
              <el-button
                  class="link-btn"
                  link
                  type="primary"
                  @click="openSubPage(row,2)"
              >查看
              </el-button>
              <el-button
                  class="link-btn"
                  link
                  type="primary"
                  v-if="row.status == 1"
                  @click="openSubPage(row,3)"
              >自评
              </el-button>
              <el-button
                  class="link-btn"
                  link
                  type="primary"
                  v-if="row.status==2"
                  @click="openSubPage(row,4)"
              >评定
              </el-button>
            <el-popconfirm
                class="link-btn"
                title="是否通过?"
                confirmButtonText="确定"
                cancelButtonText="取消"
                @confirm="() => reviewanySub2(row)"
            >
              <template #reference>
                  <span>
                      <el-button
                          class="link-btn"
                          link
                          type="primary"
                          v-if="row.status==3">
                  通过
                </el-button>
                  </span>
              </template>
            </el-popconfirm>
              <el-button
                  class="link-btn"
                  link
                  type="primary"
                  v-if="row.status==3"
                  @click="reviewOne(row,1)">驳回
              </el-button>
          </template>
        </table-common>
      </layout-card>
    </div>
    <!--  设置弹窗   -->
    <edit-dialog
      :centerDialogVisible="isDialog"
      tilte="设置绩效考核截止日期"
      align-center
      :defaultButton="false"
      :width="'400'"
      @Cancel="handleClose"
    >
      <template #content>
        <el-form ref="form" :model="timeForm" label-width="160px" label-position="left">
          <el-form-item label="绩效考核截止日期："> 每月 <el-input v-model="timeForm.assessDate" style="width: 80px"></el-input> 日
          </el-form-item>
          <el-form-item label="自动发布日期：">
            每月 <el-input v-model="timeForm.publicDate" style="width: 80px"></el-input> 日
          </el-form-item>
          <el-form-item label="到期自动发布：">
              <el-radio-group v-model="timeForm.publicStatus">
            <el-radio :label=1>是</el-radio>
            <el-radio :label=2>否</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="员工自评截止日期：">
            每月 <el-input v-model="timeForm.selfDate" style="width: 80px"></el-input> 日
          </el-form-item>
          <el-form-item label="到期自动提交：">
              <el-radio-group v-model="timeForm.selfStatus">
            <el-radio  :label=1>是</el-radio>
            <el-radio  :label=2>否</el-radio>
              </el-radio-group>
          </el-form-item>
        </el-form>
      </template>
      <template #custom>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary"  @click="handleSave" :loading="handleSaveLaoding">添加</el-button>
        </span>
      </template>
    </edit-dialog>
      <edit-dialog
          :centerDialogVisible="reviewDialog"
          :tilte="reviewTitle"
          align-center
          :defaultButton="false"
          :width="'400'"
          @Cancel="reviewHandleClose"
      >
          <template #content>
              <el-form  label-position="left" @submit.native.prevent>
                  <el-form-item label="驳回意见：">
                      <el-input v-model="reviewMessage" style="width: 100%" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" maxlength="200" show-word-limit></el-input>
                  </el-form-item>
              </el-form>
          </template>
          <template #custom>
        <span class="dialog-footer">
          <el-button @click="reviewHandleClose">取消</el-button>
          <el-button type="primary"  @click="reviewanySub">提交</el-button>
        </span>
          </template>
      </edit-dialog>
  </div>
</template>
<script lang="ts" setup>

import {ref, reactive, onMounted, watch, computed, nextTick, onUnmounted} from 'vue'
import LayoutCard from '@/views/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import editDialog from '@/components/editDialog/index.vue'
import { exampleColumns } from '@/views/quality/performanc/config/columns'
import { exampleOptions } from '@/views/quality/performanc/config/filters'
import {getDeadlinelist, getPersonLst, onReview, onReviewFn, updateDeadlinelist, exportList} from "@/api/quality/performanc";

import router from '@/router'
import {dayjs, ElMessage, ElTree} from 'element-plus'
import {Search} from "@element-plus/icons-vue";

import {useStore} from "vuex";

// 获取组织架构
const {getters} = useStore();
const organizes1=computed(() => getters['user/getOrganTree']);
const organizes = ref(JSON.parse(JSON.stringify(organizes1.value)));

/**
 * @Name: 变量区域
 * @Author: cdfy2
 * @Date: 2023/15/06  15:52:06
 */
// 表格数据
const list = ref([])
//表格加载
const loading = ref(false)
// 分页
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 0
})
// 排序
const order = ref([{
  "column": 'status',
  "method": 'desc'
}])
// 查询参数
const retrievedForm = ref({
    attendanceMonth: null,//考核周期
    updateTime:[],//更新时间
    staffName:null, // 姓名
    staffNumber:null, // 员工编号
    status:null,//状态
});
interface Tree {
  [key: string]: any
}
const filterText = ref('')
const treeRefs=ref<any>(null)
const reviewDialog=ref(false)
watch(filterText, (val) => {
    console.log(val);
    treeRefs.value!.filter(val)
})
interface RuleForm {
  radio1: string
  radio2: string
  yue1: string
  yue2: string
  yue3: string
}
const timeForm = ref({})
const treeData = ref<Tree[]>([])
const defaultProps = {
  children: 'children',
  label: 'name'
}
// 获取树形结构
const geTreeData = () => {
    treeData.value = organizes.value
    ergodicTree(treeData.value);
    getTopOne(treeData.value[0])
}
const ergodicTree=(datas:any)=>{
    datas.forEach((item:any)=>{
        if(item.children.length>0){
            item.name=item.organizationName
            ergodicTree(item.children)
        }else{
            item.id=item.organizationId
            item.name=item.organizationName
            item.catalogueId=item.organizationId
            item.children=[]
        }
    })
};

// 导出
const exportLoading = ref(false); // 导出按钮加载动画
const exportBtn = ()=> {
    exportLoading.value = true
    const orderValue = {...order.value}
    const payload = {
        attendanceMonth:retrievedForm.value.attendanceMonth,
        collation:orderValue[0].method,
        endTime:retrievedForm.value.updateTime[1],
        id:null,
        orderBy:orderValue[0].column,
        organId:currentNodeData.value.id,
        staffName:retrievedForm.value.staffName,
        staffNumber:retrievedForm.value.staffNumber,
        startTime:retrievedForm.value.updateTime[0],
        status:retrievedForm.value.status
    }
    exportList(payload).then(res=>{
        exportLoading.value=false
        const fileName = "绩效考核信息列表"  + ".xlsx"; // 自定义文件名
        const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=utf-8", // 文件格式
        });
        const link = document.createElement("a"); // 创建下载链接
        link.href = URL.createObjectURL(blob);
        link.download = `${fileName}`;
        link.click();
        URL.revokeObjectURL(link.href);
        link.remove();

    }).finally(()=>{
        exportLoading.value=false;
    })
}

// 获取信息列表中的选中数据
const batchBtn = ref<boolean>(true);
const patchBtn=ref(true)
const selectData=ref([])
const selectTable = ref([]);
const handleSelectionChange = (e:any)=> {
    selectTable.value = e;
    batchBtn.value=false
    patchBtn.value=false
    e.forEach((item=>{
        if(item.status!=3){
            batchBtn.value=true
        }
        if(item.status!=0){
            patchBtn.value=true
        }
    }))
    if(e.length==0){
        batchBtn.value=true
        patchBtn.value=true
    }
    selectData.value=e
}
//驳回与通过
const reviewTitle=ref("")
const reviewMessage=ref("")
const reviewStatus=ref(0)
const review=async (index: number) => {
    reviewDialog.value=true
    reviewTitle.value=index==0?'通过':'驳回'
    reviewStatus.value=index
}
const reviewOne=(row,index)=>{
    reviewDialog.value=true
    reviewTitle.value=index==0?'通过':'驳回'
    reviewStatus.value=index
    selectData.value=[row]
}
const reviewHandleClose=()=>{
    reviewDialog.value=false
    reviewMessage.value=''
}
//发布
const patchPublish=(row:any)=>{
    if(row){
        selectData.value=[row]
    }
    reviewStatus.value=1
    reviewHandleOk()
}
//审核确认
const reviewHandleOk=async () => {
    let ids: any[] = []
    selectData.value.forEach(item => {
        ids.push(item.id)
    })
    const res = await onReview({
        ids: ids,
        reviewOpinion:reviewMessage.value,
        status:reviewStatus.value
    })
    if (res?.code === '1') {
        ElMessage.success("操作成功");
        reviewHandleClose()
        onGetSpaceList(currentNodeData.value);
    }else{
        ElMessage.error(res?.message || '操作失败，请重试！');
    }
}

const reviewanySub2 = (row:any)=> {
    reviewStatus.value = 0
    selectData.value= [row]
    reviewanySub();
}

const reviewanySub3 = ()=> {
    reviewStatus.value = 0
    selectData.value= selectTable.value
    reviewanySub();
}

const patchPublish2 = async ()=> {
    let ids: any[] = []
    selectTable.value.forEach(item => {
        ids.push(item.id)
    })
    const res = await onReview({
        ids: ids,
        reviewOpinion:reviewMessage.value,
        status:1
    })
    if (res?.code === '1') {
        ElMessage.success("操作成功");
        reviewHandleClose()
        onGetSpaceList(currentNodeData.value);
    }else{
        ElMessage.error(res?.message || '操作失败，请重试！');
    }
}

const reviewanySub=async () => {
    let ids: any[] = []
    selectData.value.forEach(item => {
        ids.push(item.id)
    })
    const res = await onReviewFn({
        ids: ids,
        reviewOpinion:reviewMessage.value,
        reviewStatus:reviewStatus.value
    })
    if (res?.code === '1') {
        ElMessage.success("操作成功");
        reviewHandleClose()
        onGetSpaceList(currentNodeData.value);
    }else{
        ElMessage.error(res?.message || '操作失败，请重试！');
    }
}

//默认选中组织目录第一个
const currentNodeData = ref();
const currentNodeKey=ref("")
const getTopOne=(data:any)=>{
    if(data.children&&data.children.length>0){
        getTopOne(data.children[0])
    }else{
        nextTick(()=>{
            currentNodeKey.value= data.id
            currentNodeData.value = data;
            if (typeof sessionStorage['sionCurrenNodeData'] === 'undefined') {
                treeRefs.value.setCurrentKey(currentNodeKey.value);
                onGetSpaceList(currentNodeData.value);
            } else {
                const sionCurrenNodeData = JSON.parse(sessionStorage['sionCurrenNodeData'])
                treeRefs.value.setCurrentKey(sionCurrenNodeData);
                currentNodeData.value.id = sionCurrenNodeData;
                const aData = {
                    id: sionCurrenNodeData
                }
                onGetSpaceList(aData);
            }
        })
        return
    }
}
// 查询列表信息
const onGetSpaceList= async (data: any) => {
    loading.value = true;
    const orderValue = {...order.value}
    const payload = {
        pageNum: pager.currentPage,
        pageSize: pager.pageSize,
        condition: {
            attendanceMonth:retrievedForm.value.attendanceMonth,
            collation:orderValue[0].method,
            endTime:retrievedForm.value.updateTime[1],
            id:null,
            orderBy:orderValue[0].column,
            organId:data.id,
            staffName:retrievedForm.value.staffName,
            staffNumber:retrievedForm.value.staffNumber,
            startTime:retrievedForm.value.updateTime[0],
            status:retrievedForm.value.status
        }
    }
    const res = await getPersonLst(payload);
    if (res?.code === '1') {
        list.value = res.data.list;
        list.value.forEach((item)=>{
            if (item.score < 60) {
                item.rating = "不合格"
            } else if (item.score >= 60 && item.score < 100) {
                item.rating = "基本合格"
            } else if (item.score >= 100 && item.score < 102) {
                item.rating = "良好"
            } else if (item.score >= 102) {
                item.rating = "优秀"
            }
        })
        pager.total = res.data.total;
        pager.pageCount =
            Math.ceil(pager.total / pager.pageSize) === 0
                ? 1
                : Math.ceil(pager.total / pager.pageSize);
    }
    loading.value = false;
}
// 点击树形结构切换列表
const handleNodeClick=(row:any)=>{
    currentNodeData.value= row
    onGetSpaceList(currentNodeData.value);
};
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}
const isDialog = ref(false);
// 取消按钮
const handleClose = ()=> {
  isDialog.value = false;
}
const openTimeDialog = (data:any) => {
  isDialog.value = true
    getDeadlinelist().then(res=>{
        if(res.code=='1'){
            timeForm.value=res.data
        }
    })
}
const handleSaveLaoding = ref<boolean>(false)
const handleSave=async () => {
    handleSaveLaoding.value = true;
    const res = await updateDeadlinelist(timeForm.value)
    if (res?.code === '1') {
        ElMessage.success("设置成功");
        handleSaveLaoding.value = false;
        isDialog.value=false
    }else{
        ElMessage.error(res?.message || '操作失败，请重试！');
        handleSaveLaoding.value = false;
    }
}
/**
 * @Name: 分页
 * @Author: cdfy2
 * @Date: 2023/15/06  15:53:29
 * @param val 当前页码
 */
const changeCurrent = (val: number) => {
    pager.currentPage = val
    onGetSpaceList(currentNodeData.value);
}

/**
 * @Name: 内容
 * @Author: cdfy2
 * @Date: 2023/15/06  15:54:26
 * @param val 每页展示多少条
 */
const changePageSize = (val: number) => {
    pager.currentPage = 1;
    pager.pageSize = val
    onGetSpaceList(currentNodeData.value);
}
/**
 * @Name: 排序事件
 * @Author: cdfy2
 * @Date: 2023/15/06  15:57:55
 * @param data 传入的某一列的列名和升降序
 */
const sortChange = (data: any) => {
    pager.currentPage = 1;
    const method = data.order==='descending'?'desc':'asc';
    order.value=[{ column:
            data.prop=='employeeId'?'employeeId':
                data.prop=='addPoints'?'addPoints':
                    data.prop=='deductPoints'?'deductPoints':
                        data.prop=='score'?'score':
                            data.prop=='award'?'award':
                                data.prop=='deductions'?'deductions':
                                    data.prop=='updateTime'?'updateTime':
                                        data.prop=='status'?'status': data.prop, method, }];
    onGetSpaceList(currentNodeData.value);
}
/**
 * @Name: 获取表格数据
 * @Author: cdfy2
 * @Date: 2023/15/06  15:58:25
 */
const pageInfo = () => {
    // 这里也应该查第一页
    pager.currentPage = 1;
    onGetSpaceList(currentNodeData.value);
}
/**
 * @Name: 重置方法
 * @Author: cdfy2
 * @Date: 2023/15/06  15:58:48
 */
const searchReset = () => {
    retrievedForm.value = {
        attendanceMonth: null,//考核周期
        updateTime: [],//更新时间
        staffName: null, // 姓名
        staffNumber: null, // 员工编号
        status: null,//状态
    }
    order.value = [{
        "column": 'updateTime',
        "method": 'desc'
    }]
    pager.currentPage = 1;
    pager.pageSize = 10;
    onGetSpaceList(currentNodeData.value);
}
/**
 * @functionName: 内容
 * @Author: cdfy2
 * @Date: 2023/15/06  15:29:48
 * @param row 传入的某一列的列名和升降序
 * @param type 打开弹窗的类型 0：自评  1：新增奖惩记录 2：查看
 */
const openSubPage = (row: any, type: number) => {
    // sessionStorage.setItem('sionCurrenNodeData',JSON.stringify(currentNodeData.value))
    router.push({
        path: '/quality/performanc/add',
        query: { row:JSON.stringify(row),type:type }
    })
}
/**
 * @Name: 挂载dom后操作
 * @Author: cdfy2
 * @Date: 2023/15/06  15:55:00
 */
onMounted(() => {
    geTreeData();
})
onUnmounted(()=> {
    if (typeof sessionStorage['sionCurrenNodeData'] === 'undefined') {
        return
    } else {
        sessionStorage.removeItem('sionCurrenNodeData');//清除缓存
    }
})
</script>
<style lang="less" scoped>
.organization {
  display: flex;
  .organizationLeft {
    width: 310px;
    display: flex;
    .companyTree {
      flex: 1;
      min-width: 230px;
      max-width: 230px;
      padding: 24px;
      margin: 12px 0 12px 24px;
      background: #fff;
      border-radius: 8px;
      overflow-x: auto;
      .title {
        font-size: 16px;
        position: relative;
        padding-left: 5px;
        border-left: 2px solid #2e7cf1;
        font-family: "HarmonyOS_Sans_SC_Medium";
        color: #353a42;
        line-height: 24px;
        font-weight: bolder;
        margin-bottom: 24px;
      }
      .search {
        margin-bottom: 24px;
      }
    }
  }
  .organizationRight {
    display: flex;
    width: 81%;
  }

}

</style>
<style>
.companyTree .el-tree-node > .el-tree-node__children {
  overflow: visible;
}
.companyTree::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}
.companyTree::-webkit-scrollbar-thumb {
  background-color: #dddee0;
}
.companyTree .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background-color: #cce5f0;
  color: #027db4;
  padding-right: 24px;
}
.companyTree  .el-tree > :nth-child(n+1) {
  display: inline-block;
  min-width: 100%;
  padding-right: 24px;
}
</style>
